<template>
  <div class="custom-table-container">
    <!-- 自定义列按钮 -->
    <div class="table-actions" v-if="showCustomColumnBtn || showSelection">
      <div class="selection-info" v-if="showSelection">
        <span v-if="selectedRows.length" class="selected-text">当前已选择 {{ selectedRows.length }} 行 |</span>
        <span v-if="selectedRows.length" type="primary" class="selected-text-btn" link @click="clearSelection">清空已选</span>
      </div>
      
    </div>

    <!-- 表格主体 -->
    <div class="table-main-container">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="data"
		    :height="tableHeight"
        @selection-change="handleSelectionChange"
        class="main-table"
        :row-class-name="getRowClassName"
        v-bind="$attrs"
      >
        <!-- 序号列 -->
        <el-table-column v-if="showIndex" type="index" label="序号" width="60">
          <template #header>
              <el-icon v-if="showCustomColumnBtn" @click="showCustomColumnDialog" size="20">
                <img
                  :src="setting"
                  class="button-image"
                />
              </el-icon>
              <span v-else>序号</span>
          </template>
        </el-table-column>
        <!-- 选择列 -->
        <el-table-column v-if="showSelection" type="selection" width="55"></el-table-column>
       
        <!-- 动态列 -->
        <template v-for="column in visibleColumns" :key="column.prop">
          <el-table-column
            :prop="column.prop"
            :label="column.label"
            :width="column.width || 'auto'"
            :min-width="column.minWidth || 'auto'"
            :fixed="column.fixed || (column.prop === 'operation' ? 'right' : false)"
          >
            <!-- 表头自定义插槽 -->
            <template #header="scope">
              <slot
                :name="`${column.prop}-header`"
                :column="column"
                :index="scope.$index"
              >
                {{ column.label }}
              </slot>
            </template>

            <!-- 默认插槽 - 用户可以通过具名插槽覆盖 -->
            <template #default="scope">
              <!-- 检查是否有该列的具名插槽 -->
              <slot
                :name="column.prop"
                :row="scope.row"
                :index="scope.$index"
                :column="column"
              >
                <!-- 日期选择器插槽 -->
                <template v-if="(column.prop === 'produceTime' || column.prop === 'expireTime')&&column.defaultSlot">
                  <el-date-picker
                    v-model="scope.row[column.prop]"
                    type="date"
                    :placeholder="`请选择${column.label}`"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :clearable="true"
                    @change="(val) => handleDateChange(val, column.prop, scope.row)"
                  />
                </template>
                <!-- 批次号输入框插槽 -->
                <template v-else-if="column.prop === 'batchNo'&&column.defaultSlot">
                  <el-input
                    v-model="scope.row[column.prop]"
                    :placeholder="`请输入${column.label}`"
                    size="small"
                    @change="(val) => handleInputChange(val, column.prop, scope.row)"
                  />
                </template>
                <!-- 如果是操作列且有图标配置，显示图标 -->
                <template v-else-if="column.prop === 'operation' && column.icons">
                  <el-button v-throttle-click="2000"
                    v-for="(icon, index) in column.icons"
                    :key="index"
                    :type="icon.type || 'primary'"
                    :icon="icon.name"
                    :size="icon.size || 'small'"
                    :circle="icon.circle || false"
                    :plain="icon.plain || false"
                    :disabled="icon.disabled || false"
                    @click="icon.click && icon.click(scope.row, scope.$index)"
                    class="operation-icon-btn"
                  >
                    {{ icon.text }}
                  </el-button>
                </template>
                
                <!-- 非操作列或没有图标配置时显示默认内容 -->
                <template v-else>
                  {{ scope.row[column.prop] }}
                </template>
              </slot>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="showPagination">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :layout="paginationLayout"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 自定义列弹窗 -->
    <el-dialog
      v-model="customColumnDialogVisible"
      title="自定义列"
      width="750px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="custom-column-container">
        <div class="column-header">
          <div class="header-item">#</div>
          <div class="header-item">列名</div>
          <div class="header-item">列宽</div>
          <div class="header-item">操作</div>
        </div>
        <div class="column-body">
          <!-- 拖拽排序组件 -->
          <draggable 
            v-model="dialogColumnSettings" 
            item-key="prop"
            handle=".column-row"
            :disabled="false"
            ghost-class="ghost-column"
            animation="300"
            @end="onDragEnd"
          >
            <template #item="{element: column, index}">
              <div class="column-row" :class="{'drag-disabled': isOperationColumn(column)}" :draggable="!isOperationColumn(column)">
                <div class="body-item">
                  <div class="drag-handle">
                    <i class="el-icon-rank drag-icon"></i>
                    <span>{{ index + 1 }}</span>
                  </div>
                </div>
                <div class="body-item" >
                  <div class="column-name">
                    <el-checkbox v-model="column.visible">{{ column.label }}</el-checkbox>
                  </div>
                </div>
                <div class="body-item">
                  <el-input
                    v-model="column.width"
                    placeholder="自定义宽度"
                    size="small"
                    :disabled="!column.visible"
                    style="width: 100px;"
                  >
                    <template #append>px</template>
                  </el-input>
                  <span class="min-width-text" v-if="!column.width && column.minWidth">
                    最小: {{ column.minWidth }}px
                  </span>
                  <span class="min-width-text" v-if="!column.width && !column.minWidth">
                    自适应
                  </span>
                </div>
                <div class="body-item">
                  <div class="column-actions">
                    <el-tooltip content="上移" placement="top" :hide-after="500">
                      <el-button v-throttle-click="2000"
                        :disabled="index === 0 || isOperationColumn(column)"
                        circle
                        size="small"
                        @click="moveColumnUp(index)"
                      >
                        <el-icon><ArrowUp /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="下移" placement="top" :hide-after="500">
                      <el-button v-throttle-click="2000"
                        :disabled="index === columnsSetting.length - 1 || isOperationColumn(column) || isLastBeforeOperation(index)"
                        circle
                        size="small"
                        @click="moveColumnDown(index)"
                      >
                        <el-icon><ArrowDown /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="置顶" placement="top" :hide-after="500">
                      <el-button v-throttle-click="2000"
                        :disabled="index === 0 || isOperationColumn(column)"
                        circle
                        size="small"
                        @click="moveColumnTop(index)"
                      >
                        <el-icon><Top /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="置底" placement="top" :hide-after="500">
                      <el-button v-throttle-click="2000"
                        :disabled="index === columnsSetting.length - 1 || isOperationColumn(column) || isLastBeforeOperation(index)"
                        circle
                        size="small"
                        @click="moveColumnBottom(index)"
                      >
                        <el-icon><Bottom /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </template>
          </draggable>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-throttle-click="2000" @click="cancelCustomColumn">取消</el-button>
          <el-button v-throttle-click="2000" @click="resetColumnSettings">重置</el-button>
          <el-button v-throttle-click="2000" type="primary" @click="saveCustomColumns">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { Setting, ArrowUp, ArrowDown, Top, Bottom } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true
  },
  // 表格列配置
  columns: {
    type: Array,
    required: true
  },
  // 是否显示自定义列按钮
  showCustomColumnBtn: {
    type: Boolean,
    default: true
  },
  // 是否显示选择列
  showSelection: {
    type: Boolean,
    default: true
  },
  // 是否显示序号列
  showIndex: {
    type: Boolean,
    default: true
  },
  // 表格加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true
  },
  // 当前页码
  currentPage: {
    type: Number,
    default: 1
  },
  // 每页显示条数
  pageSize: {
    type: Number,
    default: 10
  },
  // 可选的每页显示条数
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100]
  },
  // 分页布局
  paginationLayout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  // 总条数
  total: {
    type: Number,
    default: 0
  },
  // 表格唯一标识，用于本地存储
  tableId: {
    type: String,
    default: ''
  },
  // 表格高度，设置了高度后可以固定表头
  tableHeight: {
    type: [String,Number],
    default: '50vh'
  },
  // 行数据唯一标识字段
  rowKey: {
    type: String,
    default: 'recId'
  },
  // 是否高亮显示选中行
  highlightSelectedRow: {
    type: Boolean,
    default: true
  },
  // 选中行背景颜色
  selectedRowBgColor: {
    type: String,
    default: ''
  }
})
// 停用图片
const setting = ref(
  new URL("@/assets/images/setting.png", import.meta.url).href
);
const emit = defineEmits([
  'update:currentPage',
  'update:pageSize',
  'size-change',
  'current-change',
  'selection-change',
  'column-change',
  'date-change',
  'input-change'
])

const tableRef = ref(null)

// 自定义列相关
const customColumnDialogVisible = ref(false)
const columnsSetting = ref([])
const visibleColumns = ref([])
const defaultColumnsSetting = ref([])
// 临时存储列设置，用于取消操作
let tempColumnSettings = null
// 弹窗中临时编辑的列设置
const dialogColumnSettings = ref([])
// 存储选中的行
const selectedRows = ref([])

// 初始化表格列配置
const initTableColumns = () => {
  // 深拷贝列配置
  columnsSetting.value = JSON.parse(JSON.stringify(props.columns))
 
  // 为每个列添加visible属性（如果没有）
  columnsSetting.value.forEach(column => {
    if (column.visible === undefined) {
      column.visible = true
    }
  })

  // 备份默认配置用于重置
  defaultColumnsSetting.value = JSON.parse(JSON.stringify(columnsSetting.value))

  // 确保操作列始终在最后面
  ensureOperationColumnLast()

  // 更新可见列
  updateVisibleColumns()

  // 从本地存储中加载配置
  if (props.tableId) {
    try {
      const savedColumns = localStorage.getItem(`table_columns_${props.tableId}`)
      if (savedColumns) {
        const parsedColumns = JSON.parse(savedColumns)
        
        // 检查是否有变化的列
        const savedColumnProps = parsedColumns.map(col => col.prop)
        const currentColumnProps = columnsSetting.value.map(col => col.prop)
        
        // 找出新增的列
        const newColumns = columnsSetting.value.filter(col => !savedColumnProps.includes(col.prop))
        
        // 找出删除的列
        const deletedColumnProps = savedColumnProps.filter(prop => !currentColumnProps.includes(prop))
        
        let hasChanges = false
        let updatedColumns = [...parsedColumns]
        
        // 处理删除的列
        if (deletedColumnProps.length > 0) {
          updatedColumns = updatedColumns.filter(col => !deletedColumnProps.includes(col.prop))
          hasChanges = true
        }
        
        // 处理新增的列
        if (newColumns.length > 0) {
          hasChanges = true
          
          // 找出操作列的位置
          const operationIndex = updatedColumns.findIndex(col => col.prop === 'operation')
          
          if (operationIndex !== -1) {
            // 如果缓存中有操作列，将新列插入到操作列之前
            for (const newColumn of newColumns) {
              updatedColumns.splice(operationIndex, 0, newColumn)
            }
          } else {
            // 如果缓存中没有操作列，直接添加到末尾
            updatedColumns.push(...newColumns)
          }
        }
        
        if (hasChanges) {
          // 保存更新后的列配置到本地存储
          localStorage.setItem(`table_columns_${props.tableId}`, JSON.stringify(updatedColumns))
        }
        
        // 应用更新后的列配置
        columnsSetting.value = updatedColumns
        
        // 确保操作列始终在最后面
        ensureOperationColumnLast()
        
        // 更新可见列
        updateVisibleColumns()
      }
    } catch (e) {
      console.error('加载表格列配置失败', e)
    }
  }
}

// 判断一个列是否是操作列
const isOperationColumn = (column) => {
  return column && column.prop === 'operation'
}

// 检查是否有操作列
const hasOperationColumn = computed(() => {
  return columnsSetting.value.some(column => column.prop === 'operation')
})

// 判断是否是操作列之前的最后一列
// 这个函数用于确保操作列前的最后一列不能向下移动或置底，
// 保证操作列始终保持在表格最右侧的位置
const isLastBeforeOperation = (index) => {
  const operationIndex = dialogColumnSettings.value.findIndex(col => col.prop === 'operation')
  // 如果没有操作列，或者当前索引不是操作列的前一个位置，返回false
  return operationIndex !== -1 && index === operationIndex - 1
}

// 确保操作列始终在最后面
const ensureOperationColumnLast = () => {
  const operationIndex = columnsSetting.value.findIndex(col => col.prop === 'operation')
  if (operationIndex !== -1 && operationIndex !== columnsSetting.value.length - 1) {
    const temp = columnsSetting.value.splice(operationIndex, 1)[0]
    columnsSetting.value.push(temp)
  }
}

// 移动列
const moveColumnUp = (index) => {
  // 不允许移动操作列
  if (isOperationColumn(dialogColumnSettings.value[index])) return

  if (index > 0) {
    // 不允许与操作列互换位置
    if (isOperationColumn(dialogColumnSettings.value[index - 1])) return

    const temp = dialogColumnSettings.value[index - 1]
    dialogColumnSettings.value[index - 1] = dialogColumnSettings.value[index]
    dialogColumnSettings.value[index] = temp
  }
}

const moveColumnDown = (index) => {
  // 不允许移动操作列
  if (isOperationColumn(dialogColumnSettings.value[index])) return

  if (index < dialogColumnSettings.value.length - 1) {
    // 不允许与操作列互换位置
    if (isOperationColumn(dialogColumnSettings.value[index + 1])) return

    const temp = dialogColumnSettings.value[index + 1]
    dialogColumnSettings.value[index + 1] = dialogColumnSettings.value[index]
    dialogColumnSettings.value[index] = temp
  }
}

const moveColumnTop = (index) => {
  // 不允许移动操作列
  if (isOperationColumn(dialogColumnSettings.value[index])) return

  const temp = dialogColumnSettings.value[index]
  dialogColumnSettings.value.splice(index, 1)
  dialogColumnSettings.value.unshift(temp)

  // 如果操作列存在，确保它仍在最后
  ensureOperationColumnInDialog()
}

const moveColumnBottom = (index) => {
  // 不允许移动操作列
  if (isOperationColumn(dialogColumnSettings.value[index])) return

  const temp = dialogColumnSettings.value[index]
  dialogColumnSettings.value.splice(index, 1)

  // 如果有操作列，在操作列前插入
  const operationIndex = dialogColumnSettings.value.findIndex(col => col.prop === 'operation')
  if (operationIndex !== -1) {
    dialogColumnSettings.value.splice(operationIndex, 0, temp)
  } else {
    dialogColumnSettings.value.push(temp)
  }
}

// 确保弹窗中操作列始终在最后
const ensureOperationColumnInDialog = () => {
  const operationIndex = dialogColumnSettings.value.findIndex(col => col.prop === 'operation')
  if (operationIndex !== -1 && operationIndex !== dialogColumnSettings.value.length - 1) {
    const temp = dialogColumnSettings.value.splice(operationIndex, 1)[0]
    dialogColumnSettings.value.push(temp)
  }
}

// 拖拽结束后的处理
const onDragEnd = () => {
  // 确保操作列始终在最后
  ensureOperationColumnInDialog()
}

// 更新可见列
const updateVisibleColumns = () => {
  visibleColumns.value = columnsSetting.value.filter(column => column.visible)
  // 通知父组件列配置发生变化
  emit('column-change', columnsSetting.value)
}

// 显示自定义列弹窗
const showCustomColumnDialog = () => {
  // 创建临时副本，确保取消时不会影响原有设置
  tempColumnSettings = JSON.parse(JSON.stringify(columnsSetting.value))
  // 创建弹窗中使用的临时编辑副本
  dialogColumnSettings.value = JSON.parse(JSON.stringify(columnsSetting.value))
  customColumnDialogVisible.value = true
}

// 取消自定义列设置
const cancelCustomColumn = () => {
  customColumnDialogVisible.value = false
}

// 重置当前弹窗中的列设置到默认状态
const resetColumnSettings = () => {
  dialogColumnSettings.value = JSON.parse(JSON.stringify(defaultColumnsSetting.value))
}

// 保存自定义列配置
const saveCustomColumns = () => {
  // 将弹窗中的设置应用到实际表格
  columnsSetting.value = JSON.parse(JSON.stringify(dialogColumnSettings.value))
  updateVisibleColumns()
  customColumnDialogVisible.value = false

  // 保存到本地存储
  if (props.tableId) {
    try {
      localStorage.setItem(`table_columns_${props.tableId}`, JSON.stringify(columnsSetting.value))
    } catch (e) {
      console.error('保存表格列配置失败', e)
    }
  }
}

// 处理选择事件
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 清空选择
const clearSelection = () => {
  if (tableRef.value) {
    try {
      // 使用Element Plus表格实例的clearSelection方法
      tableRef.value.clearSelection()
      // 重置选中数组
      selectedRows.value = []
      emit('selection-change', [])
    } catch (error) {
      console.error('清空选择失败', error)
    }
  } else {
    // 如果表格引用不存在，直接重置选中数组
    selectedRows.value = []
    emit('selection-change', [])
  }
}

// 设置选中行 - 新增方法
const setSelectedRows = async (rows, rowKey = props.rowKey) => {
  if (!rows || rows.length === 0) return false
  
  // 确保表格已渲染
  if (!tableRef.value) {
    await nextTick()
    if (!tableRef.value) {
      console.warn('表格尚未渲染，无法设置选中行')
      return false
    }
  }
  
  try {
    // 先清除现有选择
    tableRef.value.clearSelection()
    
    let rowsToSelect = []
    
    // 根据rowKey是否存在选择不同的匹配方式
    if (!rowKey) {
      // 如果没有rowKey，则尝试使用索引位置匹配
      // 注意：这种方式仅在行数据顺序未变化时有效
      rowsToSelect = rows.map(row => {
        const index = typeof row === 'number' ? row : props.data.indexOf(row)
        return index >= 0 ? props.data[index] : null
      }).filter(row => row !== null)
    } else {
      // 使用行数据的唯一标识符找到对应的行数据
      rowsToSelect = props.data.filter(row => {
        return rows.some(selectedRow => 
          selectedRow[rowKey] === row[rowKey]
        )
      })
    }
    
    // 对找到的行设置选中状态
    rowsToSelect.forEach(row => {
      tableRef.value.toggleRowSelection(row, true)
    })
    
    // 更新内部选中状态
    selectedRows.value = rowsToSelect
    
    // 通知父组件选择变化
    emit('selection-change', rowsToSelect)
    
    return true
  } catch (error) {
    console.error('设置选中行失败', error)
    return false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  emit('update:pageSize', size)
  emit('size-change', size)
  emit('getDataList')
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  emit('update:currentPage', page)
  emit('current-change', page)
  emit('getDataList')
}

// 处理日期变化
const handleDateChange = (val, prop, row) => {
  // 可以在这里添加日期变化的处理逻辑
  console.log('日期变化:', prop, val, row)
  // 如果需要，可以在这里触发事件通知父组件
  emit('date-change', { prop, value: val, row })
}

// 处理输入框变化
const handleInputChange = (val, prop, row) => {
  // 可以在这里添加输入变化的处理逻辑
  console.log('输入变化:', prop, val, row)
  // 如果需要，可以在这里触发事件通知父组件
  emit('input-change', { prop, value: val, row })
}

// 获取行的class名称
const getRowClassName = ({ row, rowIndex }) => {
  // 判断是否开启了高亮显示
  if (props.highlightSelectedRow) {
    // 如果rowKey为空，则使用行索引作为唯一标识
    if (!props.rowKey) {
      // 判断当前行的索引是否在选中的行索引数组中
      if (selectedRows.value.some((_, index) => index === rowIndex)) {
        console.log('props.rowKey空',props.rowKey)
        return 'selected-row'
      }
    } else {
      // 判断当前行是否在选中的行数组中（使用rowKey）
      if (selectedRows.value.some(selectedRow => selectedRow[props.rowKey] === row[props.rowKey])) {
        return 'selected-row'
      }
    }
  }
  return ''
}

// 监听props.columns变化
watch(() => props.columns, (newColumns) => {
  if (newColumns) {
    initTableColumns()
  }
}, { deep: true })

// 监听数据变化，在数据变化时可能需要重新设置选中状态
watch(() => props.data, () => {
  // 数据变化时，可能需要重新计算选中状态
  // 这里不直接实现，而是通过暴露的方法让使用者来控制
}, { deep: false })

// 页面初始化
onMounted(() => {
  initTableColumns()
})

// 暴露方法供父组件使用
defineExpose({
  clearSelection,
  setSelectedRows,
  tableRef,
  selectedRows,
  // 添加重置列配置的方法
  resetColumnsStorage: () => {
    if (props.tableId) {
      try {
        // 删除本地存储中的列配置
        localStorage.removeItem(`table_columns_${props.tableId}`)
        // 重新初始化列配置
        initTableColumns()
        return true
      } catch (e) {
        console.error('重置列配置失败', e)
        return false
      }
    }
    return false
  },
  // 添加获取列配置状态的方法
  getColumnsState: () => {
    const result = {
      currentColumns: columnsSetting.value,
      storedColumns: null,
      defaultColumns: defaultColumnsSetting.value
    }
    
    if (props.tableId) {
      try {
        const savedColumns = localStorage.getItem(`table_columns_${props.tableId}`)
        if (savedColumns) {
          result.storedColumns = JSON.parse(savedColumns)
        }
      } catch (e) {
        console.error('获取存储的列配置失败', e)
      }
    }
    
    return result
  }
})
</script>

<style lang="scss" scoped>
.button-image {
    width: 20px;
    height: 20px;
    object-fit: contain;
    margin-right: 4px;
    vertical-align: middle;
}
.custom-table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;

  /* 选中行高亮样式 */
  :deep(.selected-row) {
    --el-table-tr-bg-color: v-bind('props.selectedRowBgColor || "var(--el-color-primary-light-9, #ecf5ff)"');
  }

  .table-actions {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .selection-info {
      display: flex;
      align-items: center;

      .selected-text {
        font-size: 14px;
        color: #909399;
        margin-right: 10px;
      }

	  .selected-text-btn{
		  font-size: 14px;
		  color: var(--primary-color);
	  }

    }

	.table-actions-btn{
		margin-left: auto;
	}
  }

  .table-main-container {
    flex: 1;
    min-height: 200px; /* 确保最小高度，避免表格过小时布局异常 */
    overflow: hidden; /* 防止子元素溢出 */

    .main-table {
      width: 100%;
      /* 确保固定列正确显示 */
      :deep(.el-table__fixed-right) {
        height: 100%;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 10 !important;
        box-shadow: -5px 0 10px rgba(0, 0, 0, 0.12);
      }

      :deep(.el-table__fixed-right-patch) {
        position: absolute;
        top: 0;
        right: 0;
        background-color: #fff;
        z-index: 1 !important;
      }

      /* 修复操作列透视问题 */
      :deep(.el-table__fixed-right .el-table__fixed-body-wrapper) {
        background-color: #fff !important;
      }

      :deep(.el-table__fixed-right .el-table__cell) {
        background-color: #fff !important;
      }

      :deep(.el-table-fixed-column--right) {
        background-color: #fff !important;
        z-index: 1 !important;
      }

      :deep(.el-table-fixed-column--right.is-first-column) {
        background-color: #fff !important;
        z-index: 1 !important;
      }

      :deep(.el-table__fixed-right .cell) {
        background-color: #fff !important;
      }

      :deep(.el-table__fixed-right tr:hover .el-table__cell) {
        background-color: rgba(0, 0, 0, 0.04) !important;
      }

      :deep(.el-table__fixed-header-wrapper) {
        z-index: 12 !important;
      }
    }
  }

  .pagination-container {
    margin-top: 15px;
    padding: 5px 0;
    display: flex;
    justify-content: flex-end;
    background-color: #fff;
    z-index: 10;
    position: sticky;
    right: 0;
    bottom: 0;
    width: 100%;
  }

  .custom-column-container {
    margin-top: 5px;
    border: 1px solid #ebeef5;
    border-radius: 4px;

    .column-header {
      display: flex;
      align-items: center;
      background-color: #f5f7fa;
      padding: 10px;
      border-bottom: 1px solid #ebeef5;
      font-weight: bold;

      .header-item {
        &:nth-child(1) {
          flex: 0 0 40px;
          text-align: center;
        }
        &:nth-child(2) {
          flex: 2;
          padding-left: 10px;
        }
        &:nth-child(3) {
          flex: 1;
          text-align: center;
        }
        &:nth-child(4) {
          flex: 2;
          text-align: center;
        }
      }
    }

    .column-body {
      max-height: 400px;
      overflow-y: auto;

      .column-row {
        display: flex;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid #ebeef5;
        cursor: move;
        position: relative;
        
        &::before {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="%23ccc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/></svg>') 12px center no-repeat;
          opacity: 0;
          transition: opacity 0.2s;
          z-index: 0;
        }
        
        &:hover::before {
          opacity: 0.5;
        }

        &.drag-disabled {
          cursor: not-allowed;
          
          &::before {
            display: none;
          }
        }

        .body-item {
          position: relative;
          z-index: 1;
          
          &:nth-child(1) {
            flex: 0 0 40px;
            text-align: center;
            
            .drag-handle {
              display: flex;
              align-items: center;
              justify-content: center;
              
              .drag-icon {
                margin-right: 5px;
                color: #909399;
              }
            }
          }
          &:nth-child(2) {
            flex: 2;
            padding-left: 10px;
          }
          &:nth-child(3) {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;

            .min-width-text {
              font-size: 12px;
              color: #909399;
              margin-top: 5px;
            }
          }
          &:nth-child(4) {
            flex: 2;

            .column-actions {
              display: flex;
              justify-content: center;
              gap: 5px;
              
              .el-button {
                position: relative;
                z-index: 2;
                
                &:hover, &:focus, &:active {
                  z-index: 3;
                }
              }
            }
          }
        }

        &:last-child {
          border-bottom: none;
        }
      }
    }
  }
}

/* 修复操作列表头边框，使用更强的CSS选择器确保优先级 */
:deep(body) .el-table__fixed-right .el-table__fixed-header-wrapper th.el-table-fixed-column--right {
  border-top: 1px solid #EBEEF5 !important;
  background-color: #fff !important;
  border-bottom: 1px solid #EBEEF5 !important;
}

:deep(body) .el-table__fixed-right .el-table__fixed-header-wrapper th.el-table-fixed-column--right.is-first-column {
  border-top: 1px solid #EBEEF5 !important;
  background-color: #fff !important;
  border-bottom: 1px solid #EBEEF5 !important;
}

:deep(body) .el-table__fixed-right .el-table__fixed-header-wrapper th.el-table-fixed-column--right.is-first-column.is-leaf {
  border-top: 1px solid #EBEEF5 !important;
  background-color: #fff !important;
  border-bottom: 1px solid #EBEEF5 !important;
}

:deep(body) .el-table__fixed-right .el-table__fixed-header-wrapper th[class*="el-table_"][class*="_column_"][class*="el-table-fixed-column--right"] {
  border-top: 1px solid #EBEEF5 !important;
  background-color: #fff !important;
  border-bottom: 1px solid #EBEEF5 !important;
}

/* 使用内联样式插入到表格组件运行时，确保最高优先级 */
:deep(.el-table) .el-table__header-wrapper::after {
  content: "";
  display: none;
}

:deep(html) {
  --table-fixed-right-border-color: #EBEEF5;
  --table-fixed-right-bg-color: #fff;
}

:deep(.main-table) .el-table .el-table__header th.el-table-fixed-column--right[class*="el-table_"],
:deep(.main-table) .el-table .el-table__header th.el-table-fixed-column--right.is-first-column,
:deep(.main-table) .el-table .el-table__header th.el-table-fixed-column--right.is-leaf {
  border-top: 1px solid var(--table-fixed-right-border-color, #EBEEF5) !important;
  background-color: var(--table-fixed-right-bg-color, #fff) !important;
  border-bottom: 1px solid var(--table-fixed-right-border-color, #EBEEF5) !important;
}

/* 拖拽相关样式 */
:deep(.ghost-column) {
  opacity: 0.5;
  background: #e8f4ff;
  border: 1px dashed #409eff;
}

:deep(.sortable-drag) {
  opacity: 0;
}

/* 操作列图标按钮样式 */
.operation-icon-btn {
  margin-right: 8px;
  
  &:last-child {
    margin-right: 0;
  }
  
  &:hover {
    transform: scale(1.05);
    transition: transform 0.2s ease;
  }
}
</style>

<style lang="scss">
/* 全局样式，确保最高优先级 */
.el-table__fixed-right .el-table__fixed-header-wrapper th.el-table-fixed-column--right,
.el-table__fixed-right .el-table__fixed-header-wrapper th.el-table-fixed-column--right.is-first-column,
.el-table__fixed-right .el-table__fixed-header-wrapper th.el-table-fixed-column--right.is-leaf,
.el-table__fixed-right .el-table__fixed-header-wrapper th[class*="el-table_"][class*="_column_"][class*="el-table-fixed-column--right"] {
  border-top: 1px solid #EBEEF5 !important;
  background-color: #fff !important;
  border-bottom: 1px solid #EBEEF5 !important;
}

/* 强制应用特定样式 */
.el-table__fixed-right thead tr:first-child th.el-table-fixed-column--right {
  border-top: 1px solid #EBEEF5 !important;
}

/* 使用直接的元素选择器而不是类选择器 */
thead tr th[class*="el-table-fixed-column--right"] {
  border-top: 1px solid #EBEEF5 !important;
}
</style>
